<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="采购方式">
              <j-search-select-tag-new placeholder="请选择" v-model="queryParam.purchaseWay" dictCode="purchase_way" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库">
              <j-url-select
                v-model="queryParam.warehouse"
                placeholder="请选择"
                :multiple="true"
                url="/hzkj-wms/wms/warehouse/list?pageNo=1&pageSize=9999&type=1"
                :optionDiy="optionWarehouseDiy"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="平台付款状态">
              <j-search-select-tag-new
                placeholder="请选择"
                v-model="queryParam.paymentStatus"
                dictCode="purchase_payment_status"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="供应商">
              <a-input placeholder="请输入供应商名称" v-model="queryParam.supplierName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="单据编号">
              <a-input placeholder="请输入单据编号" v-model="queryParam.orderNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="SKU编号">
              <a-input placeholder="请输入SKU编号" v-model="queryParam.skuCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="跟踪号">
              <a-input placeholder="请输入跟踪号" v-model="queryParam.trackingNumber"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="单据状态">
                <j-search-select-tag-new
                  placeholder="请选择"
                  :multiple="true"
                  v-model="queryParam.orderStatus"
                  dictCode="purchase_order_status"
                />
              </a-form-item>
            </a-col>
            <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="工单进度">
                <j-search-select-tag-new
                  placeholder="请选择"
                  v-model="queryParam.paymentStatus"
                  dictCode="purchase_order_status"
                />
              </a-form-item>
            </a-col> -->
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="是否收货异常">
                <j-search-select-tag-new
                  placeholder="请选择"
                  v-model="queryParam.isReceivedAbnormal"
                  :dictOptions="[
                    { value: 'Y', text: '是' },
                    { value: 'N', text: '否' },
                  ]"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="采购人">
                <j-url-select v-model="queryParam.purchaser" placeholder="请选择" url="/sys/user/getAllUsernameByOrg" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="成本中心">
                <j-url-select
                  placeholder="请选择成本中心"
                  :multiple="true"
                  v-model="queryParam.costCenterId"
                  url="/sys/costCenter/queryAllByUserId"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="结算类型">
                <j-search-select-tag-new
                  placeholder="请选择"
                  v-model="queryParam.settlementType"
                  dictCode="purchase_settlement_type"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="结算方式">
                <j-search-select-tag-new
                  placeholder="请选择"
                  v-model="queryParam.settlementWay"
                  dictCode="purchase_settlement_way"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="支付方式">
                <j-search-select-tag-new
                  placeholder="请选择"
                  v-model="queryParam.paymentWay"
                  dictCode="purchase_payment_way"
                />
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-tabs v-model="queryParam.status" @change="searchQuery">
      <a-tab-pane v-for="item in dictStatusOption" :key="item.value" :tab="item.text" />
    </a-tabs>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator" style="margin-top: 10px">
      <a-button
        v-has="'PurchaseOrderList:add'"
        v-if="queryParam.status == '1'"
        @click="
          editId = ''
          showEditModal = true
        "
        type="primary"
        icon="plus"
        >创建采购单</a-button
      >
      <a-button
        v-has="'PurchaseOrderList:pay1688'"
        v-if="queryParam.status == '1'"
        type="primary"
        @click="payOrderBatch(null, '1')"
        >1688下单</a-button
      >
      <a-button
        v-has="'PurchaseOrderList:cancel1688'"
        v-if="queryParam.status == '1'"
        type="primary"
        @click="batchPlaceOrder1688()"
        >取消1688订单</a-button
      >
      <a-button v-has="'PurchaseOrderList:add'" type="primary" @click="clickCopyOrder">复制采购单</a-button>
      <a-button v-has="'PurchaseOrderList:export'" type="primary" icon="download" @click="handleExportXls('采购单')"
        >导出</a-button
      >
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <div class="table-wrap">
        <a-table
          ref="table"
          rowKey="id"
          bordered
          :expandIconColumnIndex="-1"
          :expandIconAsCell="false"
          :expandedRowKeys.sync="expandedRowKeys"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          @change="handleTableChange"
        >
          <template #orderMsgSlot="text, record">
            <div>
              单号：<a @click="$refs.orderDetailModal.api_open(record.id, record)" style="margin-right: 20px">{{
                record.orderNo
              }}</a>
              <template v-if="record.status == '1'">
                <a-tag v-if="record.paymentStatus == '1'" color="blue">1688未下单</a-tag>
                <a-tag v-if="record.paymentStatus == '2'" color="orange">1688未付款</a-tag>
                <a-tag v-if="record.paymentStatus == '3'" color="red">1688下单失败</a-tag>
              </template>
              <a-tag v-if="record.status == '4' && record.receivedQuantity != record.totalPurchaseQuantity" color="red"
                >收货异常</a-tag
              >
            </div>
            <div>成本：{{ record.costCenterId_dictText }}</div>
            <div>备注：{{ record.remark }}</div>
            <div>仓库留言：{{ record.warehouseRemark }}</div>
          </template>
          <template #purchaseWaySlot="text, record">
            <span :style="{ color: record.purchaseWay == 1 ? 'orange' : 'green' }">{{
              record.purchaseWay_dictText
            }}</span>
          </template>
          <template #contentTitle>
            采购内容
            <a-button
              v-show="expandedRowKeys.length != dataSource.length"
              type="link"
              icon="down"
              @click="toggleExpandAll()"
              title="展开全部"
            ></a-button>
            <a-button
              v-show="expandedRowKeys.length == dataSource.length"
              type="link"
              icon="up"
              @click="toggleExpandAll()"
              title="收起全部"
            ></a-button>
          </template>
          <template #contentSlot="text, record">
            <div v-for="(item, index) in record.productConciseInfos || []" :key="index">{{ item }}</div>
            <div v-if="record.productConciseInfos.length > 4">
              ...+{{ record.productDetailCount - record.productConciseInfos.length }}
            </div>
            <div style="text-align: right">
              <a-button
                v-show="!expandedRowKeys.includes(record.id)"
                type="link"
                icon="down"
                @click="toggleExpand(record)"
                >展开</a-button
              >
              <a-button v-show="expandedRowKeys.includes(record.id)" type="link" icon="up" @click="toggleExpand(record)"
                >收起</a-button
              >
            </div>
          </template>
          <template #warehouseSlot="text, record">
            <div>库名：{{ record.warehouse_dictText }}</div>
            <div>计划：{{ record.totalPurchaseQuantity }}</div>
            <div>在途：{{ record.transitQuantity }}</div>
            <div>待上架：{{ record.pendingListingQuantity }}</div>
            <div>已上架：{{ record.alreadyListedQuantity }}</div>
          </template>
          <template #moneyTitle>
            费用(元)
            <a-tooltip placement="top" :overlayStyle="{ 'min-Width': '580px' }">
              <template #title>
                <div>产品总价：单据所有SKU初始订单付款金额，包含产品退款金额。</div>
                <div>运费总价：单据初始运费总价，包含退款金额。</div>
                <div>总金额：单据当前实际总费用，不包含退款金额。（退：当前单据产品退款+运费退款。）</div>
                <div>上架金额：所有SKU产品单价*上架数量之和，上架数量≥采购数量时，按采购数量计算。</div>
              </template>
              <a-icon type="info-circle" />
            </a-tooltip>
          </template>
          <template #moneySlot="text, record">
            <div>产品总价：{{ record.productTotalPrice }}</div>
            <div>运费总价：{{ record.totalShippingFee }}</div>
            <div>
              总金额：{{ record.totalAmount }}
              <span v-if="record.isRefund == '1'" class="c-red">(退:{{ record.refundAmount }})</span>
            </div>
            <div>上架金额：{{ record.listedAmount }} (含良品:{{ record.notDefectsAmount }})</div>
          </template>
          <template #logisticsSlot="text, record">
            <div>方式：{{ record.transportWay_dictText }}</div>
            <div>
              <span>跟踪号：</span>
              <a-popover trigger="hover" placement="top" title="跟踪号">
                <template #content>
                  <div v-for="(item, index) in record.trackingNumberArr" :key="index">
                    {{ item }}
                    <a-button style="width: 16px; height: 16px" type="link" icon="copy" @click="copyTo(item)" />
                  </div>
                </template>
                <template v-for="(item, index) in record.trackingNumberArr">
                  <span :key="index" v-if="index < 4">
                    {{ item }}
                    <a-button style="width: 16px; height: 16px" type="link" icon="copy" @click="copyTo(item)" />
                  </span>
                </template>
                <span v-if="record.trackingNumberArr.length > 4">...</span>
              </a-popover>
            </div>
          </template>
          <template #workOrderSlot>
            <div>工单数量：</div>
            <a>查看</a>
          </template>
          <template #paySlot="text, record">
            <div>类型：{{ record.settlementType_dictText }}</div>
            <div>方式：{{ record.settlementWay_dictText }}</div>
            <div>支付：{{ record.paymentWay_dictText }}</div>
          </template>
          <template #peopleSlot="text, record">
            <div>采购人：{{ record.purchaser }}</div>
            <div>创建人：{{ record.createBy }}</div>
          </template>
          <template #timeSlot="text, record">
            <div>预计到货：{{ record.expectArrivalTime }}</div>
            <div>创建：{{ record.createTime }}</div>
            <div>更新：{{ record.updateTime || record.createTime }}</div>
          </template>

          <template #finishStatusSlot="text, record">
            <div v-if="record.finishCause">
              <div class="c-red">强制完成</div>
              <div>({{ record.finishCause }})</div>
            </div>
            <div v-else>正常完成</div>
          </template>
          <template #orderStatusSlot="text, record">
            <a-tag :color="colorStatus[record.status]"> {{ record.status_dictText }} </a-tag>
          </template>

          <span slot="action" slot-scope="text, record">
            <a
              v-has="'PurchaseOrderList:edit'"
              v-if="record.status == '1' && (record.purchaseWay == '2' || record.paymentStatus != '2')"
              @click="
                editId = record.id
                showEditModal = true
              "
              >编辑</a
            >
            <a
              v-has="'PurchaseOrderList:editNumber'"
              v-if="['2', '3', '4', '5'].includes(record.status)"
              @click="$refs.trackingModal.api_open(record.id, record.trackingNumber)"
              >管理跟踪号</a
            >
            <a v-has="'PurchaseOrderList:del'" v-if="record.status == '6'" @click="clickDelete(record)">删除</a>

            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
              <a-menu slot="overlay">
                <a-menu-item
                  v-has="'PurchaseOrderList:pay'"
                  v-if="record.status == '1' && record.paymentStatus != '2'"
                >
                  <a @click="payOrderBatch(record, record.purchaseWay)">下单</a>
                </a-menu-item>
                <a-menu-item v-has="'PurchaseOrderList:complete'" v-if="['2', '3', '4'].includes(record.status)">
                  <a @click="$refs.forceCompleteModal.api_open(record.id, record.orderNo)">强制完成</a>
                </a-menu-item>
                <a-menu-item v-has="'PurchaseOrderList:change'" v-if="record.status == '3'">
                  <a
                    @click="
                      editId = record.id
                      showChangeModal = true
                    "
                    >变更</a
                  >
                </a-menu-item>
                <a-menu-item
                  v-has="'PurchaseOrderList:cancel'"
                  v-if="record.status == '1' && record.paymentStatus != '2'"
                >
                  <a @click="$refs.cancelOrderModal.api_open(record.id, record.orderNo)">取消</a>
                </a-menu-item>
                <a-menu-item v-has="'PurchaseOrderList:log'">
                  <j-operate-log :id="record.id" />
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>

          <!-- 以下是采购单下的产品子表单 -->
          <template #expandedRowRender="record">
            <div class="table-expand">
              <div class="search-box">
                <a-input-search
                  placeholder="输入SKU、产品名称关键词"
                  size="small"
                  v-model="record.searchKey"
                  @change="searchChange(record)"
                />
              </div>
              <a-table
                :columns="innerColumns(record)"
                :loading="record.skuLoading"
                rowKey="skuCode"
                :dataSource="record.skuItemsFilterList"
                :pagination="false"
              >
                <template #imgSlot="text2, record2">
                  <a-popover trigger="hover" placement="right">
                    <template #content>
                      <div class="popover-preview-box">
                        <img :src="record2.imgUrl" />
                      </div>
                    </template>
                    <viewer :images="[record2.imgUrl]" class="img-box">
                      <img v-show="record2.imgUrl" class="sku-img" :src="record2.imgUrl" />
                    </viewer>
                  </a-popover>
                </template>
                <template #supplierLinkSlot="text2, record2">
                  <div>供应商：{{ record2.supplierName }}</div>
                  <div class="link-item">
                    <div>采购链接：</div>
                    <a-tooltip :overlayStyle="{ 'min-Width': '700px' }">
                      <template slot="title"> {{ record2.url || '-' }} </template>
                      <div class="link">
                        <a
                          v-if="/^(https?:\/\/)/.test(record2.url)"
                          :href="record2.url"
                          target="_blank"
                          >{{ record2.url }}</a
                        >
                        <span v-else>{{ record2.url || '-' }}</span>
                      </div>
                    </a-tooltip>
                  </div>
                </template>
                <template #supplierAttrSlot="text2, record2">
                  <div v-if="record2.supplierType == 1">
                    <div v-for="item1 in record2.attribute" :key="item1.attributeID">
                      {{ item1.attributeName }}：
                      <span v-for="(val2, index2) in item1.checkVal" :key="index2">{{ val2 }}；</span>
                    </div>
                  </div>
                  <div v-else>{{ record2.attribute || '-' }}</div>
                </template>
                <template #specSlot="text2, record2">
                  <div>
                    供应商规格:
                    <span :class="{ 'c-red': record2.specsSup > 1 }">{{ record2.specsSup }}</span
                    >/组
                  </div>
                  <div>
                    入库规格:<span :class="{ 'c-red': record2.specsMy > 1 }">{{ record2.specsMy }}</span
                    >/组
                  </div>
                </template>
              </a-table>
            </div>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 新增，编辑采购单 -->
    <order-modal v-if="showEditModal" :visible.sync="showEditModal" :editId="editId" @submit="modalFormOk" />
    <!-- 采购单详情 -->
    <order-detail-modal ref="orderDetailModal" />
    <!-- 变更采购单 -->
    <change-modal v-if="showChangeModal" :visible.sync="showChangeModal" :editId="editId" @submit="modalFormOk" />
    <!-- 取消下单弹窗 -->
    <cancel-order-modal ref="cancelOrderModal" @submit="modalFormOk" />
    <!-- 强制完成弹窗 -->
    <force-complete-modal ref="forceCompleteModal" @submit="modalFormOk" />
    <!-- 跟踪号弹窗 -->
    <tracking-modal ref="trackingModal" @submit="modalFormOk" />
    <!-- 1688下单弹窗 -->
    <pay-order-1688-modal ref="payOrder1688Modal" @submit="modalFormOk" />
  </a-card>
</template>

<script>
import copyToClipboard from 'copy-to-clipboard'
import { formatAmount } from '@/utils/number'
import { getAction, postAction, deleteAction } from '@/api/manage'

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import OrderModal from './modules/OrderModal.vue'
import ChangeModal from './modules/ChangeModal.vue'
import CancelOrderModal from './modules/CancelOrderModal.vue'
import ForceCompleteModal from './modules/ForceCompleteModal.vue'
import TrackingModal from './modules/TrackingModal.vue'
import PayOrder1688Modal from './modules/PayOrder1688Modal.vue'
import OrderDetailModal from './modules/OrderDetailModal.vue'

export default {
  name: 'PurchaseOrderInfoList',
  mixins: [JeecgListMixin],
  components: {
    OrderModal,
    ChangeModal,
    CancelOrderModal,
    ForceCompleteModal,
    PayOrder1688Modal,
    TrackingModal,
    OrderDetailModal,
  },
  data() {
    return {
      editId: '',
      showEditModal: false,
      showChangeModal: false,
      dictStatusOption: [],
      expandedRowKeys: [],
      url: {
        list: '/hzkj-purchase/purchase/order/info/list',
        skuList: '/hzkj-purchase/purchase/product/batchUnfold',
        exportXlsUrl: '/hzkj-purchase/purchase/order/info/exportXls',
        importExcelUrl: 'purchase/order/info/importExcel',
        queryStatusData: '/hzkj-purchase/purchase/order/info/queryStatusCount',
        batchPlaceOrder: '/hzkj-purchase/purchase/order/info/batchPlaceOrder',
        batchPlaceOrder1688: '/hzkj-purchase/purchase/order/info/batchCancelOrder1688',
        copyOrder: '/hzkj-purchase/purchase/order/info/copyOrder',
        delete: '/hzkj-purchase/purchase/order/info/delete',
      },
      queryParam: {
        status: '1',
      },
      colorStatus: {
        1: 'orange',
        2: 'cyan',
        3: 'blue',
        4: 'purple',
        5: 'green',
        6: 'pink',
      },
    }
  },
  computed: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    columns() {
      let arr = [
        {
          title: '序号',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '单据信息',
          align: 'left',
          width: 300,
          scopedSlots: { customRender: 'orderMsgSlot' },
        },
        {
          title: '采购方式',
          align: 'center',
          width: 100,
          dataIndex: 'purchaseWay_dictText',
          scopedSlots: { customRender: 'purchaseWaySlot' },
        },
        !this.queryParam.status
          ? {
              title: '单据状态',
              align: 'center',
              width: 150,
              scopedSlots: { customRender: 'orderStatusSlot' },
            }
          : null,
        {
          align: 'left',
          width: 180,
          slots: { title: 'contentTitle' },
          scopedSlots: { customRender: 'contentSlot' },
        },
        {
          title: '仓库',
          align: 'left',
          width: 130,
          dataIndex: 'warehouse_dictText',
          scopedSlots: { customRender: 'warehouseSlot' },
        },
        {
          align: 'left',
          width: 220,
          slots: { title: 'moneyTitle' },
          scopedSlots: { customRender: 'moneySlot' },
        },
        {
          title: '物流快递',
          align: 'left',
          width: 150,
          scopedSlots: { customRender: 'logisticsSlot' },
        },
        // {
        //   title: '工单',
        //   align: 'center',
        //   width: 120,
        //   scopedSlots: { customRender: 'workOrderSlot' },
        // },
        {
          title: '结算方式',
          align: 'left',
          width: 130,
          scopedSlots: { customRender: 'paySlot' },
        },
        this.queryParam.status == '5'
          ? {
              title: '完成状态',
              align: 'center',
              width: 150,
              scopedSlots: { customRender: 'finishStatusSlot' },
            }
          : null,
        {
          title: '人员/组织',
          align: 'left',
          width: 160,
          scopedSlots: { customRender: 'peopleSlot' },
        },
        {
          title: '时间',
          align: 'left',
          width: 180,
          scopedSlots: { customRender: 'timeSlot' },
        },
        !!this.queryParam.status
          ? {
              title: '操作',
              dataIndex: 'action',
              align: 'center',
              width: 160,
              scopedSlots: { customRender: 'action' },
            }
          : null,
      ]
      return arr.filter((i) => i)
    },
    innerColumns() {
      return (recordItem) => {
        let arr = [
          {
            title: '序号',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender(t, r, index) {
              return parseInt(index) + 1
            },
          },
          {
            title: 'SKU编号',
            align: 'center',
            width: 140,
            dataIndex: 'skuCode',
          },
          {
            title: '主图',
            width: 105,
            dataIndex: 'imgSlot',
            scopedSlots: { customRender: 'imgSlot' },
          },
          {
            title: '产品名称',
            align: 'center',
            width: 140,
            dataIndex: 'nameCn',
          },
          {
            title: '颜色/尺寸',
            align: 'center',
            width: 140,
            dataIndex: 'name',
            customRender(t, record) {
              return record.color + ';' + record.size
            },
          },
          {
            title: '单品规格(cm)',
            align: 'center',
            width: 140,
            dataIndex: 'singleSpec',
          },
          {
            title: '质检方式',
            align: 'center',
            width: 140,
            customRender(t, record) {
              if (record.qualityType == 1) {
                return '免检'
              } else if (record.qualityType == 3) {
                return '全检'
              } else {
                return '抽检'
              }
            },
          },
          {
            title: '供应商/采购链接',
            align: 'left',
            width: 300,
            scopedSlots: { customRender: 'supplierLinkSlot' },
          },
          {
            title: '供应商属性',
            align: 'left',
            width: 300,
            scopedSlots: { customRender: 'supplierAttrSlot' },
          },
          {
            title: '采购入库关系',
            width: 140,
            scopedSlots: { customRender: 'specSlot' },
          },
          recordItem.purchaseWay == '1'
            ? {
                title: '供应商下单数量',
                align: 'center',
                width: 120,
                dataIndex: 'orderQuantity',
                customRender(t, record) {
                  if (!record.purchaseQuantity || !record.specsMy || !record.specsSup) {
                    return '-'
                  }
                  return formatAmount((record.purchaseQuantity * record.specsMy) / record.specsSup, 4)
                },
              }
            : null,
          {
            title: '采购单价(元)',
            align: 'center',
            width: 120,
            dataIndex: 'unitPrice',
          },
          {
            title: '采购总价(元)',
            align: 'center',
            width: 120,
            customRender(t, record) {
              return formatAmount(record.unitPrice * record.purchaseQuantity)
            },
          },
          {
            title: '计划数量',
            align: 'center',
            width: 120,
            dataIndex: 'purchaseQuantity',
          },
          {
            title: '在途数量',
            align: 'center',
            width: 120,
            dataIndex: 'transitQuantity',
          },
          {
            title: '待上架数量',
            align: 'center',
            width: 120,
            dataIndex: 'pendingListingQuantity',
          },
          {
            title: '已上架数量',
            align: 'center',
            width: 120,
            dataIndex: 'alreadyListedQuantity',
          },
          {
            title: '给仓库留言',
            align: 'left',
            width: 200,
            dataIndex: 'warehouseRemark',
          },
        ]
        return arr.filter((i) => i)
      }
    },
  },
  methods: {
    // 仓库下拉框自定义
    optionWarehouseDiy({ records }) {
      return records.map((item) => {
        return {
          ...item,
          value: item.id,
          text: `${item.name}[${item.code}](${item.status == 'Y' ? '启用' : '停用'})`,
        }
      })
    },
    searchReset() {
      this.queryParam = {
        status: this.queryParam.status,
      }
      this.loadData(1)
    },
    toggleExpand(record) {
      const index = this.expandedRowKeys.indexOf(record.id)
      if (index != -1) {
        this.expandedRowKeys.splice(index, 1)
      } else {
        this.expandedRowKeys.push(record.id)
        this.loadSkuData([record])
      }
    },
    // 展开收起所有sku
    toggleExpandAll() {
      if (this.expandedRowKeys.length == this.dataSource.length) {
        this.expandedRowKeys = []
      } else {
        this.expandedRowKeys = this.dataSource.map((item) => item.id)
        this.loadSkuData(this.dataSource)
      }
    },
    //加载sku数据 若传入参数1则加载第一页的内容
    loadSkuData(records) {
      records.forEach((element) => {
        element.skuLoading = true
      })

      getAction(this.url.skuList, { orderNos: records.map((i) => i.orderNo).join(',') })
        .then((res) => {
          if (res.success) {
            records.forEach((element) => {
              element.skuItemsList = res.result[element.orderNo].map((i) => ({
                ...i,
                attribute: i.supplierType == '1' ? JSON.parse(i.attribute) : i.attribute,
              }))
              element.skuItemsFilterList = [...element.skuItemsList]
            })
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          records.forEach((element) => {
            element.skuLoading = false
          })
        })
    },
    // 加载列表数据
    loadData(arg) {
      //加载数据 若传入参数1则加载第一页的内容
      this.expandedRowKeys = []
      if (arg == 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      this.updateStatusData(params)
      this.loading = true

      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records.map((i) => ({
              ...i,
              skuItemsList: [],
              skuItemsFilterList: [],
              skuLoading: false,
              searchKey: '',
              trackingNumberArr: i.trackingNumber ? i.trackingNumber.split(',') : [],
            }))
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 更新订单的状态数量，对应的这个字典值purchase_order_status
    updateStatusData(params) {
      getAction(this.url.queryStatusData, {
        ...params,
        status: '',
      }).then((res) => {
        if (res.success) {
          this.dictStatusOption = [
            {
              value: '1',
              text: `草稿(${res.result.draftCount})`,
            },
            {
              value: '2',
              text: `已付款(${res.result.paidCount})`,
            },
            {
              value: '3',
              text: `在途(${res.result.transitCount})`,
            },
            {
              value: '4',
              text: `收货中(${res.result.receivingCount})`,
            },
            {
              value: '5',
              text: `已完成(${res.result.completedCount})`,
            },
            {
              value: '6',
              text: `已取消(${res.result.cancelledCount})`,
            },
            {
              value: undefined,
              text: `全部(${
                res.result.cancelledCount +
                res.result.completedCount +
                res.result.draftCount +
                res.result.paidCount +
                res.result.receivingCount +
                res.result.transitCount
              })`,
            },
          ]
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 筛选显示sku
    searchChange(record) {
      record.skuItemsFilterList = record.skuItemsList.filter(
        (item) => item.nameCn.indexOf(record.searchKey) > -1 || item.skuCode.indexOf(record.searchKey) > -1
      )
    },
    // 复制到剪贴板
    copyTo(value) {
      try {
        copyToClipboard(value)
        this.$message.success(`已复制：${value}`)
      } catch (e) {
        this.$message.error('复制失败')
      }
    },
    // 批量下单（只有1688的订单可以批量）
    payOrderBatch(record, type) {
      if (type == '1') {
        // 1688下单处理逻辑
        if (record) {
          this.$refs.payOrder1688Modal.api_open(record.warehouse, record.id)
        } else {
          // 1688批量下单处理逻辑
          if (!this.selectionRows.length) {
            this.$message.warning('请选择要下单的采购单')
            return
          }
          if (this.selectionRows.some((i) => i.purchaseWay != '1')) {
            this.$message.warning('选择的采购单包含不是1688采购的，请检查')
            return
          }
          if (this.$Jlodash.uniqBy(this.selectionRows, 'warehouse').length != this.selectionRows.length) {
            this.$message.warning('选择的采购单存在仓库不同，请检查')
            return
          }
          this.$refs.payOrder1688Modal.api_open(
            this.selectionRows[0].warehouse,
            this.selectionRows.map((i) => i.id).join(',')
          )
        }
      } else {
        // 其他采购不能批量
        this.$confirm({
          content: (h) => {
            return h(
              'div',
              {
                domProps: {
                  innerHTML: `<div style="padding-left: 40px;"><div style="font-weight: bold;">下单后，采购单状态变更为“${
                    record.trackingNumber ? '在途' : '已付款'
                  }”</div>你还要继续吗？</div>`,
                },
              },
              []
            )
          },
          onOk: () => {
            postAction(this.url.batchPlaceOrder, { orderIds: record.id }).then((res) => {
              if (res.success) {
                this.$message.success('下单成功')
                this.searchReset()
              } else {
                this.$message.error(res.message)
              }
            })
          },
        })
      }
    },
    // 复制采购单
    clickCopyOrder() {
      if (this.selectionRows.length == 0) {
        this.$message.warning('请选择要复制的采购单')
        return
      }
      if (this.selectionRows.length > 1) {
        this.$message.warning('一次只能复制一个采购单，请去除多余的选择')
        return
      }
      const findItem = this.selectionRows[0]
      this.$confirm({
        content: (h) => {
          return h(
            'div',
            {
              domProps: {
                innerHTML: `<div style="padding-left: 40px;"><div style="font-weight: bold;">确定对所选采购单进行复制？</div><div style="color:red;">采购单号：${findItem.orderNo}</div></div>`,
              },
            },
            []
          )
        },
        onOk: () => {
          getAction(this.url.copyOrder, { id: findItem.id }).then((res) => {
            if (res.success) {
              this.modalFormOk()
              this.$confirm({
                content: (h) => {
                  return h(
                    'div',
                    {
                      domProps: {
                        innerHTML: `<div style="padding-left: 40px;"><div style="font-weight: bold;">新采购单已生成</div><div style="color:red;">复制后采购单号：${res.result.orderNo}</div></div>`,
                      },
                    },
                    []
                  )
                },
                cancelText: '关闭',
                okText: '打开',
                onOk: () => {
                  this.editId = res.result.id
                  this.showEditModal = true
                },
              })
            } else {
              this.$message.error(res.message)
            }
          })
        },
      })
    },
    // 删除采购单
    clickDelete(record) {
      this.$confirm({
        content: (h) => {
          return h(
            'div',
            {
              domProps: {
                innerHTML: `<div style="padding-left: 40px;"><div style="font-weight: bold;">采购单号：${record.orderNo}</div><span style="color:red;">删除单据后不可恢复</span>，你还要继续吗？</div>`,
              },
            },
            []
          )
        },
        onOk: () => {
          deleteAction(this.url.delete, { id: record.id }).then((res) => {
            if (res.success) {
              //重新计算分页问题
              this.reCalculatePage(1)
              this.$message.success(res.message)
              this.loadData()
              this.onClearSelected()
            } else {
              this.$message.warning(res.message)
            }
          })
        },
      })
    },
    batchPlaceOrder1688() {
      // 1688批量下单处理逻辑
      if (!this.selectionRows.length) {
        this.$message.warning('请选择要取消的采购单')
        return
      }
      if (this.selectionRows.some((i) => i.purchaseWay != '1')) {
        this.$message.warning('选择的采购单包含不是1688采购的，请检查')
        return
      }
      if (this.selectionRows.some((i) => i.paymentStatus != '2')) {
        this.$message.warning('只有未付款的订单支持取消，请检查')
        return
      }
      this.$confirm({
        content: (h) => {
          return h(
            'div',
            {
              domProps: {
                innerHTML: `<div style="padding-left: 40px;"><div style="font-weight: bold;">已选中 ${this.selectionRows.length} 条单据</div><span style="color:red;">点击"继续"将直接取消1688所下订单且不可恢复</span>，你还要继续吗？</div>`,
              },
            },
            []
          )
        },
        onOk: () => {
          getAction(this.url.batchPlaceOrder1688, { orderIds: this.selectedRowKeys.join(',') }).then((res) => {
            if (res.success) {
              this.$message.success(`[${this.selectionRows.map((i) => i.orderNo).join(',')}]已取消成功`)
              this.modalFormOk()
            } else {
              this.$message.warning(res.message)
            }
          })
        },
      })
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
.c-red {
  color: #ff4d4f;
}
.popover-preview-box {
  width: 300px;
  height: 300px;
  position: relative;
  background-color: #fafafa;
  img {
    max-height: 100%;
    max-width: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
.img-box {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  display: inline-block;
  cursor: pointer;
  position: relative;
  background-color: #fafafa;
  img {
    width: 100%;
    height: 100%;
  }
}
.table-wrap {
  /deep/ .ant-table-body {
    width: 100%;
    max-height: 500px;
    overflow: auto;
  }
  /deep/ .ant-table-expanded-row > td {
    padding: 5px 10px 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
  }

  .table-expand {
    width: 100%;
    overflow: auto;
  }
  .search-box {
    margin-bottom: 10px;
    width: 250px;
  }
}
.link-item {
  display: flex;
  .link {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
  }
}
</style>
